import axios from 'axios';
import { message } from 'antd';
import { saveAs } from 'file-saver';
import { getToken } from '@/utils/auth';
import { blobValidate, errorCode, tansParams } from '@/utils/Z';
import { globalMessage } from './message';

const baseURL = process.env.NEXT_PUBLIC_URL;

interface DownloadOptions {
  isDelete?: boolean;
  headers?: Record<string, string>;
}

const FileDownload = {
  async name(name: string, isDelete: boolean = true) {
    const url = `${baseURL}/common/download?fileName=${encodeURIComponent(name)}&delete=${isDelete}`;
    try {
      const response = await axios({
        method: 'get',
        url,
        responseType: 'blob',
        headers: { 'Authorization': `Bearer ${getToken()}` }
      });

      const isBlob = blobValidate(response.data);
      if (isBlob) {
        const blob = new Blob([response.data]);
        this.saveAs(blob, decodeURIComponent(response.headers['download-filename']));
      } else {
        await this.printErrMsg(response.data);
      }
    } catch (error) {
      console.error('Download error:', error);
       globalMessage().error('文件下载失败');
    }
  },

  async resource(resource: string) {
    const url = `${baseURL}/common/download/resource?resource=${encodeURIComponent(resource)}`;
    try {
      const response = await axios({
        method: 'get',
        url,
        responseType: 'blob',
        headers: { 'Authorization': `Bearer ${getToken()}` }
      });

      const isBlob = blobValidate(response.data);
      if (isBlob) {
        const blob = new Blob([response.data]);
        this.saveAs(blob, decodeURIComponent(response.headers['download-filename']));
      } else {
        await this.printErrMsg(response.data);
      }
    } catch (error) {
      console.error('Resource download error:', error);
       globalMessage().error('资源下载失败');
    }
  },

  async zip(url: string, name: string) {
    const fullUrl = `${baseURL}${url}`;
    console.log(fullUrl,baseURL,url,'fullUrl')
    console.log(baseURL,'fullUrl')
    console.log(url,'fullUrl')
    try {
      const response = await axios({
        method: 'get',
        url: fullUrl,
        responseType: 'blob',
        headers: { 'Authorization': `Bearer ${getToken()}` }
      });

      const isBlob = blobValidate(response.data);
      if (isBlob) {
        const blob = new Blob([response.data], { type: 'application/zip' });
        this.saveAs(blob, name);
      } else {
        await this.printErrMsg(response.data);
      }
    } catch (error) {
      console.error('Zip download error:', error);
       globalMessage().error('压缩包下载失败');
    }
  },

  saveAs(text: Blob | string, name: string, opts?: any) {
    saveAs(text, name, opts);
  },

  async printErrMsg(data: any) {
    try {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode.default;
       globalMessage().error(errMsg);
    } catch (error) {
      console.error('Error parsing error message:', error);
       globalMessage().error('发生未知错误');
    }
  },

  // Additional method with loading indicator
  async downloadWithLoading(url: string, params: any, filename: string, config: any = {}) {
    const hideLoading = message.loading('正在下载数据，请稍候...', 0);
    
    try {
      const response = await axios.post(url, params, {
        transformRequest: [(params) => tansParams(params)],
        headers: { 
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': `Bearer ${getToken()}`
        },
        responseType: 'blob',
        ...config
      });

      const isBlob = blobValidate(response.data);
      if (isBlob) {
        const blob = new Blob([response.data]);
        this.saveAs(blob, filename);
      } else {
        await this.printErrMsg(response.data);
      }
    } catch (error) {
      console.error('Download error:', error);
       globalMessage().error('下载文件出现错误，请联系管理员！');
    } finally {
      hideLoading();
    }
  }
};

export default FileDownload;